package fun.ticsmyc.question;

import org.junit.Test;

/**
 * @author Ticsmyc
 * @date 2020-05-17 16:43
 */
public class 二分搜索 {
    /**
     * 基本的二分： 查找一个数 （不考虑边界）
     * 采用 左闭右闭方式，  左右逼近分别为 mid+1  mid-1 。
     * @param nums
     * @param target
     * @return
     */
    public static int searchOneNum(int[] nums, int target) {
        int left = 0 ;
        //1
        int right = nums.length-1;

        //2
        while(left <= right){
            int mid = left + (right - left) / 2;
            if(nums[mid] < target){
                //3
                left=mid+1;
            }else if(nums[mid]>target){
                //4
                right = mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }

    /**
     * 寻找左边界 （如果有数字，就返回第一个数字下标，如果没有，就返回这个数字左边的位置）
     * [理解为 寻找 < target的元素个数]
     * 采用左闭右开方式，  左逼近：left = mid+1 右逼近：right =mid;
     * @param nums
     * @param target
     * @return
     */
    public static int searchLeft(int[] nums, int target){
        if (nums.length == 0){
            return -1;
        }
        int left = 0;
        int right = nums.length;

        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                //向左逼近
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            }
        }
        return left;
    }



    /**
     * 寻找右边界
     * [理解为 寻找 <= target的元素个数]
     * @param nums
     * @param target
     * @return
     */
    public static int searchRight(int[] nums, int target){
        if(nums.length==0){
            return -1;
        }
        int left =0;
        int right =nums.length;
        while(left<right){
            int mid = left+(right-left)/2;
            if(nums[mid] == target){
                left = mid+1;
            }else if(nums[mid] < target){
                left = mid+1;
            }else if(nums[mid]>target){
                right = mid;
            }
        }
        return left-1;
    }



    @Test
    public void test(){
        int[] arr = new int[]{1,3,5,6,6,6,6};
        //System.out.println(searchOneNum(arr,10));
       System.out.println(searchRight(arr,6));

    }
}
